package com.example.microinvestweb.controller.transact;
import com.example.microinvestcommon.entity.UserOrder;
import com.example.microinvestcommon.pojo.Result;
import com.example.microinvestcommon.util.SnowflakeIdGeneratorUtil;
import com.example.microinvestcommon.util.ThreadLocalUtil;
import com.example.service.OrderService;
import com.example.service.UserTradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;

@RestController
@RequestMapping("/order")
//用户挂单操作
public class OrderController {

    private final UserTradeService userTradeService;
    private final SnowflakeIdGeneratorUtil snowflakeIdGeneratorUtil;
    private final OrderService orderService;

    @Autowired
    OrderController(UserTradeService userTradeService, SnowflakeIdGeneratorUtil snowflakeIdGeneratorUtil, OrderService orderService){
        this.userTradeService=userTradeService;
        this.snowflakeIdGeneratorUtil=snowflakeIdGeneratorUtil;
        this.orderService=orderService;
    }

    //挂单购买操作
    @PostMapping("/sendBuyOrder")
    public Result<String> pushBuyOrder(String stockSymbol,double orderAmount,Integer stockQuantity,double nowPrice){
        Map<String,Long> map= ThreadLocalUtil.get();
        Long userId=map.get("userId");
        UserOrder userOrder=new UserOrder(userId,stockSymbol,orderAmount,stockQuantity, UserOrder.BuySell.BUY, UserOrder.Status.ING,snowflakeIdGeneratorUtil);
        Result result=userTradeService.createBuyTradeService(userOrder,nowPrice);
        return result;
    }

    //挂单卖出操作
    @PostMapping("/sendSellOrder")
    public Result<String> pushSellOrder(String stockSymbol,double orderAmount,Integer stockQuantity,double nowPrice){
        Map<String,Long> map= ThreadLocalUtil.get();
        Long userId=map.get("userId");
        UserOrder userOrder=new UserOrder(userId,stockSymbol,orderAmount,stockQuantity, UserOrder.BuySell.SELL, UserOrder.Status.ING,snowflakeIdGeneratorUtil);
        Result result=userTradeService.createSellTradeService(userOrder,nowPrice);
        return result;
    }

    //撤单操作
    @PostMapping("/cancelOrder")
    public Result<String> cancelUserOrder(Long orderId){
        Map<String,Long> map= ThreadLocalUtil.get();
        Long userId=map.get("userId");
        Result result=orderService.cancelOrder(orderId,userId);
        return result;
    }
}
